package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.BindingAdapter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.VehicleActivityLocationBinding;
import com.qbw.app.model.Location;
import com.qbw.app.model.TravelGps;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.fragment.MapDialogFragment;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.core.observable.ObservableInt;
import com.qbw.l.L;
import com.qbw.spm.P;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import static com.qbw.app.Constant.KEY_MAP;
import static com.qbw.app.Constant.MAP_BAIDU;
import static com.qbw.app.Constant.MAP_DEFAULT;
import static com.qbw.app.Constant.MAP_GOOGLE;
import static com.qbw.app.Constant.VEHICLE_STATUS_DRIVING;
import static com.qbw.app.Constant.VEHICLE_STATUS_FLAMEOUT;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_LOCATION;

/**
 * 车辆位置
 *
 * @author QBW
 * @date 2019/8/27
 */
public class VehicleLocationActivity extends CommonActivity<VehicleActivityLocationBinding> implements OnMapReadyCallback, View.OnClickListener, View.OnLongClickListener {

    private final int COUNT_LOOP = 5;
    private GoogleMap mGoogleMap;
    private float mBaiduInitScale = 15F;
    private float mGoogleInitScale = 15F;
    private ObservableInt mSecond = new ObservableInt(-1);
    private int mCount = COUNT_LOOP;
    private BDLocation mCurrentLocation;
    private Overlay mBaiduMarker;
    private Marker mGoogleMarker;
    private static final String KEY_GPS_DATA = VehicleLocationActivity.class.getName() + "_key_gps_data";
    private boolean isUserLocation = false;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.what == 0){
                mGeneralManager.getRequestManager()
                        .getVehicleRequest()
                        .getVehicleLocation(mBinding.getLocation().getVehicleCode(),
                                VehicleLocationActivity.this)
                        .execute();
                mHandler.sendEmptyMessageDelayed(0,5000);
                return  true;
            }

            return false;
        }
    });


    public static void start(Context context, Location location) {
        Intent intent = new Intent(context, VehicleLocationActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_LOCATION, location);
        P.putString(KEY_GPS_DATA, location.getGpsDatasJson());
        location.setGpsDatas(null);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_location;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        Location location = (Location) args.getSerializable(Constant.KEY_LOCATION);
        if(location != null){
            mBinding.tvSpeed.setText((new DecimalFormat("0.0").format(location.getSpeed()))+"km/h");

        }
        mBinding.setLocation(location);
        mBinding.setSecond(mSecond);
        mBinding.title.setListener(this);
        initMap();
        mBinding.ivNavigation.setOnClickListener(this);
        mBinding.ivNavigation.setOnLongClickListener(this);
        mBinding.ivNavigationVehicle.setOnClickListener(this);
        mBinding.ivNavigationPeople.setOnClickListener(this);
        mBinding.ivRefresh.setOnClickListener(this);
        mBinding.ivAdd.setOnClickListener(this);
        mBinding.ivMinus.setOnClickListener(this);
        mBinding.vgBottom.setOnClickListener(this);
        if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
//            mHandler.post(mCountTimeRunn);
            mHandler.post(mCountTimeRunn);

        }
        if (location.getDrivingState() == Constant.VEHICLE_STATUS_INVALID) {
            location.setAddress(ResUtil.getString(R.string.no_gps_data));
        } else {
            if (TextUtils.isEmpty(location.getAddress())) {
                location.setAddress(ResUtil.getString(R.string.no_gps_data));
            }
        }
    }

//    private Runnable mGetCurrentLocationRunn = new Runnable() {
//        @Override
//        public void run() {
//            mCurrentLocation = LocationManager.getInstance().getLastLocation();
//            updateUi();
//        }
//    };

    private Runnable mCountTimeRunn = new Runnable() {
        @Override
        public void run() {
            mHandler.obtainMessage();
            mHandler.sendEmptyMessage(0);
        }
    };

    private void afterInitMap() {
        try {
            String gpsDataJson = P.getString(KEY_GPS_DATA, "");
            if (!TextUtils.isEmpty(gpsDataJson)) {
                List<TravelGps> gps = new Gson().fromJson(gpsDataJson,
                        new TypeToken<List<TravelGps>>() {}.getType());
                if (gps != null && gps.size() > 1) {
                    showTravel(gps);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            L.GL.e(e);
        }
    }

    private void showTravel(List<TravelGps> travelGpss) {
        int gpsSize = travelGpss == null ? 0 : travelGpss.size();
        L.GL.d("gpsSize[%d]", gpsSize);
        if (gpsSize < 1) {
            L.GL.w("invalid gps data size");
            return;
        }
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        if (map.equals(MAP_BAIDU)) {
            mBinding.bmapView.getMap().clear();
            TravelGps startGps = travelGpss.get(gpsSize - 1);
            TravelGps endGps = travelGpss.get(0);
            mBinding.bmapView.getMap()
                    .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                            BitmapDescriptorFactory.fromResource(R.drawable.travel_start))
                            .position(new LatLng(
                                    startGps.getLatitude(),
                                    startGps.getLongitude())))
                    .setZIndex(4);
            /*mBinding.bmapView.getMap()
                             .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                                     BitmapDescriptorFactory.fromResource(R.drawable.travel_end))
                                                                                 .position(new LatLng(
                                                                                         endGps.getLatitude(),
                                                                                         endGps.getLongitude())))
                             .setZIndex(5);*/

            TravelGps travelGps;
            List<LatLng> latLngs = new ArrayList<>();
            //int seekProgress = gpsSize - mTravelProgress;
            for (int i = gpsSize - 1; i >= 0; i--) {
                travelGps = travelGpss.get(i);
                //经纬度都是0的舍弃
                if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                    continue;
                }
                //if (i >= seekProgress) {
                latLngs.add(new LatLng(travelGps.getLatitude(), travelGps.getLongitude()));
                //}
            }

            com.baidu.mapapi.model.LatLngBounds.Builder builder = new com.baidu.mapapi.model.LatLngBounds.Builder();
            builder.include(new LatLng(startGps.getLatitude(), startGps.getLongitude()));
            builder.include(new LatLng(endGps.getLatitude(), endGps.getLongitude()));

            L.GL.e("here1，latLngs[%d],gpsSize[%d]", latLngs.size(), gpsSize);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    L.GL.e("her3");
                    //if (!mUpdateByManual) {
//                    mBinding.bmapView.getMap()
//                                     .animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(
//                                             builder.build(),
//                                             mBinding.bmapView.getWidth() - 100/*ScreenUtil.dp2px(
//                                                     VehicleLocationActivity.this,
//                                                     300)*/,
//                                             mBinding.bmapView.getHeight() - ScreenUtil.dp2px(
//                                                     VehicleLocationActivity.this,
//                                                     300)));
                    //}
                    L.GL.d("latLngs[%d]", latLngs.size());
                    if (latLngs.size() >= 2) {
                        OverlayOptions ooPolyline = new PolylineOptions().width(Constant.TRAVEL_LINE_WIDTH)
                                .color(ResUtil.getColor(
                                        R.color.travel_line_color))
                                .points(latLngs);
                        mBinding.bmapView.getMap().addOverlay(ooPolyline);
                    }
                }
            }, 500);
        } else if (map.equals(MAP_GOOGLE)) {
            if (mGoogleMap == null) {
                //mNeedShowTravel = true;
                return;
            }
            mGoogleMap.clear();
            TravelGps startGps = travelGpss.get(gpsSize - 1);
            TravelGps endGps = travelGpss.get(0);
            mGoogleMap.addMarker(new com.google.android.gms.maps.model.MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                    .fromResource(
                            R.drawable.travel_start))
                    .position(
                            new com.google.android.gms.maps.model.LatLng(
                                    startGps.getLatitude(),
                                    startGps.getLongitude())))
                    .setZIndex(4);
            /*mGoogleMap.addMarker(new com.google.android.gms.maps.model.MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                                                                                                    .fromResource(
                                                                                                            R.drawable.travel_end))
                                                                                      .position(
                                                                                              new com.google.android.gms.maps.model.LatLng(
                                                                                                      endGps.getLatitude(),
                                                                                                      endGps.getLongitude())))
                      .setZIndex(5);*/

            TravelGps travelGps;
            com.google.android.gms.maps.model.PolylineOptions polylineOptions = new com.google.android.gms.maps.model.PolylineOptions();
            for (int i = gpsSize - 1; i >= 0; i--) {
                travelGps = travelGpss.get(i);
                //经纬度都是0的舍弃
                if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                    continue;
                }
                polylineOptions.add(new com.google.android.gms.maps.model.LatLng(travelGps.getLatitude(),
                        travelGps.getLongitude()));
            }
            polylineOptions.width(Constant.TRAVEL_LINE_WIDTH)
                    .color(ResUtil.getColor(R.color.travel_line_color));
            mGoogleMap.addPolyline(polylineOptions);

            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(new com.google.android.gms.maps.model.LatLng(startGps.getLatitude(),
                    startGps.getLongitude()));
            builder.include(new com.google.android.gms.maps.model.LatLng(endGps.getLatitude(),
                    endGps.getLongitude()));
            //CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(builder.build(), 100);
            //mGoogleMap.moveCamera(cu);
        }
    }

    /**
     * 初始化定位参数配置
     */

    private void initLocationOption() {
//定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        LocationClient locationClient = new LocationClient(getApplicationContext());
//声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
        locationClient.registerLocationListener(myLocationListener);
//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        locationOption.setCoorType("bd09ll");
//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(5000);
//可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
//可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(true);
//可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(false);
//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.setLocationNotify(true);
//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true);
//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(true);
//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
//可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
//可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
//        locationOption.setIsNeedAltitude(false);
////设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
//        locationOption.setOpenAutoNotifyMode();
////设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
//        locationOption.setOpenAutoNotifyMode(3000,1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
//开始定位
        locationClient.start();
    }
    /**
     * 实现定位回调
     */
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if(location.getLatitude()>0&&location.getLongitude() >0){
                mCurrentLocation = location;
            }
            updateUi();
//            //获取纬度信息
//            double latitude = location.getLatitude();
//            //获取经度信息
//            double longitude = location.getLongitude();
//            //获取定位精度，默认值为0.0f
//            float radius = location.getRadius();
//            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
//            String coorType = location.getCoorType();
//            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
//            int errorCode = location.getLocType();

        }
    }

    private void initMap() {
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        if (MAP_BAIDU.equals(map)) {
            initBaidu();
        } else if (MAP_GOOGLE.equals(map)) {
            initGoogle();
        }
    }

    private void initBaidu() {
        mBinding.bmapView.setVisibility(View.VISIBLE);
        mBinding.bmapView.showScaleControl(false);
        mBinding.bmapView.showZoomControls(false);

        BaiduMap map = mBinding.bmapView.getMap();
        map.setMyLocationEnabled(true);
        map.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
                true,
                BitmapDescriptorFactory.fromResource(R.drawable.location_64)));
        //map.setOnMapClickListener(mBadiuMapClickListener);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(17.0f);
        map.setMapStatus(msu);
        afterInitMap();
//        mHandler.removeCallbacks(mGetCurrentLocationRunn);
//        mHandler.post(mGetCurrentLocationRunn);
        initLocationOption();

    }

    private int getTravelEndDrawable() {
        /*int d = R.drawable.travel_driving;
        Location location = mBinding.getLocation();
        if (location == null) {
            return d;
        }*/
        Location location = mBinding.getLocation();
        return VehicleDataBindingAdapter.getTravelLocationEndDrawable1(location == null ? -1 : location
                .getDrivingState());
    }

    private Bitmap getDirectionBitmap(Bitmap bitmap) {
        Location location = mBinding.getLocation();
        if (location == null) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        int bw = bitmap.getWidth();
        int bh = bitmap.getHeight();
        //matrix.postRotate((float) location.getDirection(), bw / 2, bh / 2);
        Bitmap bitmapNew = Bitmap.createBitmap(bitmap, 0, 0, bw, bh, matrix, true);
        //bitmap.recycle();
        return bitmapNew;
    }

    private void initGoogle() {
        mBinding.googleContainer.setVisibility(View.VISIBLE);
        com.google.android.gms.maps.SupportMapFragment mapFragment = (com.google.android.gms.maps.SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setCompassEnabled(false);
        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(15);
        mGoogleMap.moveCamera(cameraUpdate);
        afterInitMap();
        Location location = mBinding.getLocation();
        /*if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
            googleAnimateAndAddMarker(location.getLatitude(),
                                      location.getLongitude(),
                                      R.drawable.travel_start);
            mGoogleMarker = null;
        }*/
//        mHandler.removeCallbacks(mGetCurrentLocationRunn);
//        mHandler.post(mGetCurrentLocationRunn);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Location location = mBinding.getLocation();
        outState.putSerializable(Constant.KEY_LOCATION, location);
    }

    @BindingAdapter("vehicleLocationStatusTextColor")
    public static void setVehicleLocationStatusTextColor(TextView tv, int vehicleStatus) {
        switch (vehicleStatus) {
            case VEHICLE_STATUS_DRIVING:
                tv.setTextColor(Color.parseColor("#01BC67"));
                break;
            case VEHICLE_STATUS_FLAMEOUT:
                tv.setTextColor(Color.parseColor("#E82747"));
                break;
            /*case VEHICLE_STATUS_ILLEGAL_MOVE:
                tv.setTextColor(Color.parseColor("#E82747"));
                break;*/
            default:
                tv.setTextColor(Color.parseColor("#FEFEFF"));
                break;
        }
    }

    @BindingAdapter("vehicleLocationSpeedTextShow")
    public static void setVehicleLocationSpeedTextShow(TextView tv, int vehicleStatus) {
        tv.setVisibility(vehicleStatus == VEHICLE_STATUS_DRIVING ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        Location location = mBinding.getLocation();
        if (vid == R.id.iv_navigation) {
            /*MapDialogFragment.createInstance(location.getLatitude(), location.getLongitude())
                             .show(getSupportFragmentManager(), "");*/
            showPeopleaAndBikeNavigation(false);
        } else if (vid == R.id.iv_refresh) {
            isUserLocation = false;
            mGeneralManager.getRequestManager()
                    .getVehicleRequest()
                    .getVehicleLocation(location.getVehicleCode(), this)
                    .execute();
        } else if (vid == R.id.iv_add) {
            scaleMap(true);
        } else if (vid == R.id.iv_minus) {
            scaleMap(false);
        } else if (vid == R.id.iv_navigation_people) {
            isUserLocation = false;
            if (mGeneralManager.getMapManager().isUseBaidu()) {
//                baiduAnimateTo(mBinding.getLocation().getLatitude(),
////                        mBinding.getLocation().getLongitude());
                updateUi();
            } else {
                googleAnimateTo(mBinding.getLocation().getLatitude(),
                        mBinding.getLocation().getLongitude());
            }
            mBinding.ivNavigationPeople.setVisibility(View.INVISIBLE);
            mBinding.ivNavigationVehicle.setVisibility(View.VISIBLE);
        } else if (vid == R.id.iv_navigation_vehicle) {
            isUserLocation = true;
            if (mCurrentLocation != null) {
                if (mGeneralManager.getMapManager().isUseBaidu()) {
                    baiduAnimateToUser(mCurrentLocation.getLatitude(),
                            mCurrentLocation.getLongitude());
//                    baiduAnimateAndAddMarker(true,
//                            mCurrentLocation.getLatitude(),
//                            mCurrentLocation.getLongitude(),
//                            R.drawable.location_64);
                } else {
                    googleAnimateTo(mCurrentLocation.getLatitude(),
                            mCurrentLocation.getLongitude());
                }
            }
            mBinding.ivNavigationPeople.setVisibility(View.VISIBLE);
            mBinding.ivNavigationVehicle.setVisibility(View.INVISIBLE);
        } else if (vid == R.id.vg_bottom) {
            MapDialogFragment.createInstance(mBinding.getLocation().getLatitude(),
                    mBinding.getLocation().getLongitude())
                    .show(getSupportFragmentManager(), "");
        }
    }

    @Override
    public boolean onLongClick(View v) {
        int vid = v.getId();
        if (vid == R.id.iv_navigation) {
            showPeopleaAndBikeNavigation(true);
            return true;
        }
        return false;
    }

    private void showPeopleaAndBikeNavigation(boolean b) {
        mBinding.ivNavigationPeople.setVisibility(b ? View.VISIBLE : View.GONE);
        mBinding.ivNavigationVehicle.setVisibility(b ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (METHOD_LOCATION.equals(method)) {
            Location.Response response = (Location.Response) entity;
            Location location = response.getData();
            location.setVehicleCode(mBinding.getLocation().getVehicleCode());
            if(location.getGpsDatas()!=null && location.getGpsDatas().size()>0){
                mBinding.tvSpeed.setText((new DecimalFormat("0.0").format(location.getSpeed()))+"km/h");
            }
            mBinding.setLocation(location);
            if(!isUserLocation){
                initMap();
                showTravel(location.getGpsDatas());
            }


//            updateUi();

//            if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
//                mHandler.removeCallbacks(mCountTimeRunn);
//                mCount = COUNT_LOOP;
////                mHandler.post(mCountTimeRunn);
//            }
            closeLoadingDialog();
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        String method = httpTask.getMethod();
        if (METHOD_LOCATION.equals(method)) {
            closeLoadingDialog();
        }
    }

    private void updateUi() {
        Location location = mBinding.getLocation();
        if (!location.isGpsValid() || location
                .getGpsTime() <= 0) {
            mBinding.tvTime.setVisibility(View.GONE);
        } else {
            mBinding.tvTime.setVisibility(View.VISIBLE);
        }

        if (!location.isGpsValid()) {
            mBinding.tvAddress.setText(R.string.no_gps_data);
        }

        // 信号
        updateGpsSignal();
        updateGsmSignal();

        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        switch (map) {
            case MAP_BAIDU:
                if (location.isGpsValid()) {
                    baiduAnimateAndAddMarker(true,
                            location.getLatitude(),
                            location.getLongitude(),
                            getTravelEndDrawable());
                } else {
                    L.GL.w("车辆位置无效，显示用户当前位置");
                    if(mCurrentLocation != null) {
                        baiduAnimateAndAddMarker(true,
                                mCurrentLocation.getLatitude(),
                                mCurrentLocation.getLongitude(),
                                R.drawable.location_64);
                    } else {
                        Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(PositionUtil.BEIJING_LAT,
                                PositionUtil.BEIJING_LNG);
                        baiduAnimateAndAddMarker(true, gps.getWgLat(), gps.getWgLon(), 0);
                    }
                }
                break;
            case MAP_GOOGLE:
                if (location.isGpsValid()) {
                    googleAnimateAndAddMarker(location.getLatitude(),
                            location.getLongitude(),
                            getTravelEndDrawable());
                } else {
                    L.GL.w("车辆位置无效，显示用户当前位置");
                    if(mCurrentLocation != null) {
                        googleAnimateAndAddMarker(mCurrentLocation.getLatitude(),
                                mCurrentLocation.getLongitude(),
                                0);
                    } else {
                        //Gps gps = PositionUtil.gps84_To_Gcj02(PositionUtil.BEIJING_LAT,
                        //        PositionUtil.BEIJING_LNG);
                        //googleAnimateAndAddMarker(gps.getWgLat(), gps.getWgLon(), 0);
                        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(1);
                        mGoogleMap.moveCamera(cameraUpdate);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void scaleMap(boolean bigger) {
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        switch (map) {
            case MAP_BAIDU:
                mBaiduInitScale += (bigger ? .5F : -.5F);
                MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(mBaiduInitScale);
                mBinding.bmapView.getMap().setMapStatus(msu);
                break;
            case MAP_GOOGLE:
                mGoogleInitScale += (bigger ? .5F : -.5F);
                if (mGoogleMap != null) {
                    CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(mGoogleInitScale);
                    mGoogleMap.moveCamera(cameraUpdate);
                }
                break;
            default:
                break;
        }
    }

    private void baiduAnimateToUser(double latitude, double longitude) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }

        baiduAddMarker(true,latitude,longitude,R.drawable.location_64);

        List<LatLng> points = new ArrayList<LatLng>();//可以将多点放到list集合中
        points.add(new LatLng(latitude, longitude));//起点坐标
        points.add(new LatLng(mBinding.getLocation().getLatitude(), mBinding.getLocation().getLongitude()));//终点坐标

        com.baidu.mapapi.model.LatLngBounds.Builder builder = new com.baidu.mapapi.model.LatLngBounds.Builder();
        for (LatLng p : points) {
            builder = builder.include(p);
        }
        com.baidu.mapapi.model.LatLngBounds latlngBounds = builder.build();
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(latlngBounds);
        mBinding.bmapView.getMap().animateMapStatus(u);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomBy(-0.8f);
        mBinding.bmapView.getMap().animateMapStatus(msu);

    }


    private void baiduAnimateTo(double latitude, double longitude) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps gps = /*PositionUtil.gps84_To_Bd09(latitude, longitude)*/new Gps(latitude, longitude);
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                gps.getWgLon()));
        // 移动到某经纬度
        mBinding.bmapView.getMap().animateMapStatus(update);
    }


    /**
     * 并添加marker
     */
    private void baiduAddMarker(boolean animateTo,
                                          double latitude,
                                          double longitude,
                                          int positionDrawableRes) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        //Gps gps = PositionUtil.gps84_To_Bd09(latitude, longitude);
        Gps gps = new Gps(latitude, longitude);

        if (positionDrawableRes > 0) {
//            if (mBaiduMarker != null) {
//                mBaiduMarker.remove();
//            }
            //添加marker
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
            if (positionDrawableRes != R.drawable.travel_start && positionDrawableRes != R.drawable.travel_end && positionDrawableRes != R.drawable.travel_location) {
                bitmap = getDirectionBitmap(bitmap);
            }
            mBaiduMarker = mBinding.bmapView.getMap()
                    .addOverlay(new com.baidu.mapapi.map.MarkerOptions().anchor(
                            0.5f,
                            0.5f)
                            .position(
                                    new LatLng(
                                            gps.getWgLat(),
                                            gps.getWgLon()))
                            .icon(BitmapDescriptorFactory
                                    .fromBitmap(
                                            bitmap)));
            mBaiduMarker.setZIndex(6);
        }
    }

    /**
     * 移动到指定位置，并添加marker
     */
    private void baiduAnimateAndAddMarker(boolean animateTo,
                                          double latitude,
                                          double longitude,
                                          int positionDrawableRes) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        //Gps gps = PositionUtil.gps84_To_Bd09(latitude, longitude);
        Gps gps = new Gps(latitude-0.0025, longitude);
        if (animateTo) {
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(new LatLng(gps.getWgLat(),
                    gps.getWgLon()),17.0f);

            // 移动到某经纬度
            mBinding.bmapView.getMap().animateMapStatus(update);
        }

        if (positionDrawableRes > 0) {
            if (mBaiduMarker != null) {
                mBaiduMarker.remove();
            }
            //添加marker
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
            if (positionDrawableRes != R.drawable.travel_start && positionDrawableRes != R.drawable.travel_end && positionDrawableRes != R.drawable.travel_location) {
                bitmap = getDirectionBitmap(bitmap);
            }
            mBaiduMarker = mBinding.bmapView.getMap()
                    .addOverlay(new com.baidu.mapapi.map.MarkerOptions().anchor(
                            0.5f,
                            0.5f)
                            .position(
                                    new LatLng(
                                            latitude,
                                            longitude))
                            .icon(BitmapDescriptorFactory
                                    .fromBitmap(
                                            bitmap)));
            mBaiduMarker.setZIndex(6);
        }
    }

    private void googleAnimateTo(double latitude, double longitude) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps _gps = /*PositionUtil.gps84_To_Gcj02(latitude, longitude)*/new Gps(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);
    }

    private void googleAnimateAndAddMarker(double latitude,
                                           double longitude,
                                           int positionDrawableRes) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps _gps = /*PositionUtil.gps84_To_Gcj02(latitude, longitude)*/new Gps(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);

        if (positionDrawableRes > 0) {
            if (mGoogleMarker != null) {
                mGoogleMarker.remove();
            }
            //添加marker
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
            if (positionDrawableRes != R.drawable.travel_start && positionDrawableRes != R.drawable.travel_end && positionDrawableRes != R.drawable.travel_location) {
                bitmap = getDirectionBitmap(bitmap);
            }
            mGoogleMarker = mGoogleMap.addMarker(new MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                    .fromBitmap(bitmap))
                    .anchor(0.5f, 0.5f)
                    .position(new com.google.android.gms.maps.model.LatLng(
                            _gps.getWgLat(),
                            _gps.getWgLon())));
            mGoogleMarker.setZIndex(6);
        }
    }

    /**
     * GPS定位
     */
    private void updateGpsSignal() {
        Location location = mBinding.getLocation();
        int count = location.getSignalSpan();
//        if (count < 4) {
//            count = 0;
//        } else if (count >= 4 && count < 6) {
//            count = 1;
//        } else if (count >= 6 && count < 8) {
//            count = 2;
//        } else if (count >= 8 && count < 10) {
//            count = 3;
//        } else if (count >= 10 && count < 12) {
//            count = 4;
//        } else if (count >= 12) {
//            count = 5;
//        }
        mBinding.gpsSignal.setSignal(count, R.drawable.gps_signal_bg_gray);
    }

    /**
     * 基站定位
     */
    private void updateGsmSignal() {
        Location location = mBinding.getLocation();
        int count = location.getMcc();
        if (count < 0) {
            count = 0;
        }
        if (count > 5) {
            count = 5;
        }
        mBinding.mccSignal.setSignal(count, R.drawable.gps_signal_bg_gray);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mHandler.removeCallbacks(mCountTimeRunn);
//        mHandler.removeCallbacks(mGetCurrentLocationRunn);

    }

    @Override
    protected void onStop() {
        super.onStop();
        mHandler.removeCallbacks(mCountTimeRunn);
        mHandler.removeCallbacksAndMessages(null);
    }
}
